//
//  ProductDetailViewControllerEx.m
//  PurchasingMeeting
//
//  Created by zyhang on 4/5/14.
//  Copyright (c) 2014 YX. All rights reserved.
//

#import "ProductDetailViewControllerEx.h"

#import "DataManager.h"
#import "TKImageCache.h"
#import "SizeObject.h"
#import "DetailcellView.h"
#import "AppManager.h"
#import "PMGlobal.h"
#import "ShopViewController.h"
#import "FPPopoverController.h"
#import "UILabelStrikeThrough.h"
#import "PictureViewController.h"
#import "CopyPanel.h"

@interface ProductDetailViewControllerEx ()<NumberInputViewDelegate,UITextFieldDelegate,ZBarReaderDelegate>{
    UIView *infoView_;
    
    TKImageCache *imageCache_;
    
    ProductObject *productObject_;
    ProductObject *selectProduct_;
    ProductObject *detailProduct_;//当前屏幕下方商品详情显示的产品
    
    UIImageView *productImageV_;
    
    ShopObject *shopObj_;
    NumberInputView *inputPad_;
    
    
    UILabel *totalAmountLabel_;
    
    UIView *sizePanel_;
    
    int currentSelectType_;
    
    NSDictionary *additionProduct;
    
    UIScrollView *gridScroll_;
    
    UITextField *currentSelectInput_;
    
    NSMutableArray *currentGridProducts_;
    NSMutableArray *currentGridSizes_;
    NSMutableDictionary *currentGridOrders_;
    
    NSMutableArray *currentSubtotal_;
    NSArray *currentSizeType_;
    
    BOOL modified_;
    BOOL shouldExit_;
    
    int searchType_;
    
    UIView *backview_;
    
    NSArray *searchArray_;
    
    NSArray *allProduct_;
    
}

@end

@implementation ProductDetailViewControllerEx

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithProduct:(ProductObject *)product{
    self = [super init];
    if (self) {

        [self setup:product];
        
        shopObj_ = [[DataManager sharedManager] getCurrentShop];
        
        imageCache_ = [[TKImageCache alloc] initWithCacheDirectoryName:@"image"];
        imageCache_.notificationName = @"product_detail_image";
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(product_detail_image:)
                                                     name:@"product_detail_image"
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(coderefresh:)
                                                     name:@"coderefresh" object:nil];
    }
    return self;
}

- (void)setup:(ProductObject *)product{
    allProduct_ = [[DataManager sharedManager] getAllProduct:product];
    
    if (allProduct_.count==0) {
        return;
    }
    
    productObject_ = [allProduct_ objectAtIndex:0];
    selectProduct_ = productObject_;
#ifdef XLarge_ENABLE
    additionProduct = [[DataManager sharedManager] getAdditionalProduct:productObject_.pCode
                                                            withColorID:productObject_.pColorCode];
#else
    additionProduct = [NSMutableDictionary dictionary];
#endif
    
    
    currentGridOrders_ = [NSMutableDictionary dictionary];
    
    currentSelectInput_ = nil;
    
    currentSelectType_ = 0;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setNavTitle:@"产品详情"];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0){
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    
    [self addBackButton];
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0 green:240/255.0 blue:241/255.0 alpha:1];
    [self addInputPad];
    
    
    [self setupProduct:selectProduct_ withSizeGroup:currentSelectType_];
    
    [self addScanButton];
    [self addTotalAmountLabel];
    [self refreshSubtotal];
    
    shouldExit_ = NO;
    modified_ = NO;
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)setupProduct:(ProductObject *)obj withSizeGroup:(int)index{
    [self displayProductInfo:obj];
    
    if (sizePanel_) {
        [sizePanel_ removeFromSuperview];
    }
    
    
    NSMutableArray *products = [NSMutableArray arrayWithObjects:obj, nil];
    
    NSArray *similar = [[DataManager sharedManager] getSimiliarProduct:obj];
    [products addObjectsFromArray:similar];
    
    
    //尺码选择
    float top = 0;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0){
        top = 64;
    }
    sizePanel_ = [[UIView alloc] initWithFrame:CGRectMake(0, top, 1024, 50)];
    [self.view addSubview:sizePanel_];
    sizePanel_.backgroundColor = [UIColor grayColor];
    currentSizeType_ = [[DataManager sharedManager] getSizeTypeBySizeGroup:obj.pSizeGroupID];
    
    [self addSearchButton];
    [self addSaveButton];
    
    if (currentSizeType_.count>1) {
        for (int i = 0; i < currentSizeType_.count; i++) {
            UIButton *typeAbtn = [UIButton buttonWithType:UIButtonTypeCustom];
            typeAbtn.frame = CGRectMake(0, 0, 80, 40);
            [typeAbtn setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"anniu.png"] forState:UIControlStateNormal];
            [typeAbtn setTitle:[currentSizeType_ objectAtIndex:i] forState:UIControlStateNormal];
            typeAbtn.center = CGPointMake(0, sizePanel_.height/2);
            typeAbtn.left = i*85+20;
            [typeAbtn addTarget:self action:@selector(selectSizeType:) forControlEvents:UIControlEventTouchUpInside];
            [sizePanel_ addSubview:typeAbtn];
            typeAbtn.tag = i;
        }
    }
    
    NSArray *sizes =[[DataManager sharedManager] getSizeListBySizeGroup:obj.pSizeGroupID
                                                               SizeType:[currentSizeType_ objectAtIndex:index]];;
    
    
    
    //是否有加裤
    ProductObject *jkProduct = (ProductObject *)[additionProduct objectForKey:@"4"];
    if (jkProduct) {
        UIButton *typeAbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        typeAbtn.frame = CGRectMake(0, 0, 80, 40);
        [typeAbtn setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"anniu.png"] forState:UIControlStateNormal];
        [typeAbtn setTitle:@"单裤" forState:UIControlStateNormal];
        typeAbtn.center = CGPointMake(0, sizePanel_.height/2);
        typeAbtn.left = currentSizeType_.count*85+20;
        [typeAbtn addTarget:self action:@selector(jkClick) forControlEvents:UIControlEventTouchUpInside];
        [sizePanel_ addSubview:typeAbtn];
    }
    
    NSMutableArray *eLargeArray = [NSMutableArray array];
    ProductObject *eLarge = (ProductObject *)[additionProduct objectForKey:@"3"];
    if (eLarge) {
        [eLargeArray addObject:eLarge];
        similar = [[DataManager sharedManager] getSimiliarProduct:eLarge];
        [eLargeArray addObjectsFromArray:similar];
    }
    
    [self displayProductGrid:products xLarge:eLargeArray size:sizes];
}

#pragma mark 添加总订单量标签
- (void)addTotalAmountLabel{
    totalAmountLabel_ = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 40)];
    [self.view addSubview:totalAmountLabel_];
    totalAmountLabel_.backgroundColor = [UIColor clearColor];
    totalAmountLabel_.bottom = infoView_.top-20;
    totalAmountLabel_.right = 1024-400;
}

#pragma mark 添加返回按钮，返回的响应函数
- (void)addBackButton{
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    [b setBackgroundImage:img forState:UIControlStateNormal];
    b.frame = CGRectMake(10, 10, 99, 37);
    [b setTitle:@"返回" forState:UIControlStateNormal];
    [b addTarget:self action:@selector(toBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:b];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)showSavePopup{
    backview_ = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    backview_.userInteractionEnabled=YES;
    [self.view addSubview:backview_];
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"issavebackimage.png"];
    UIImageView *issaveview = [[UIImageView alloc]initWithImage:img];
    issaveview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    issaveview.center=CGPointMake(512, 384);
    issaveview.backgroundColor = [UIColor clearColor];
    issaveview.userInteractionEnabled = YES;
    [backview_ addSubview:issaveview];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 40)];
    title.centerX = issaveview.width/2;
    title.backgroundColor = [UIColor clearColor];
    title.top = 80;
    title.text=@"是否需要保存";
    title.font = [UIFont systemFontOfSize:25];
    title.textAlignment=UITextAlignmentCenter;
    [issaveview addSubview:title];
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    [sure setBackgroundImage:img forState:UIControlStateNormal];
    [sure setTitle:@"确定" forState:UIControlStateNormal];
    sure.frame = CGRectMake(0, 0, 90, 50);
    sure.top=165;
    sure.centerX = issaveview.width/2-90;
    [sure addTarget:self action:@selector(savePopupSave) forControlEvents:UIControlEventTouchUpInside];
    [issaveview addSubview:sure];
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setBackgroundImage:img forState:UIControlStateNormal];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    cancel.frame = CGRectMake(0, 0, sure.width, sure.height);
    cancel.top=165;
    cancel.centerX = issaveview.width/2+90;
    [cancel addTarget:self action:@selector(savePopupCancel) forControlEvents:UIControlEventTouchUpInside];
    [issaveview addSubview:cancel];
}

- (void)toBack{
    if (modified_) {
        shouldExit_ = YES;
        [self showSavePopup];
    }else{
        [self back];
    }
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 搜索按钮
- (void)addSearchButton{
    
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    UIButton *select = [UIButton buttonWithType:UIButtonTypeCustom];
    select.frame = CGRectMake(0, 0, 80, 40);
    [select setBackgroundImage:img forState:UIControlStateNormal];
    [select setTitle:@"切换" forState:UIControlStateNormal];
    select.center = CGPointMake(960, sizePanel_.height/2);
    select.right = sizePanel_.width - 10;
    [select addTarget:self action:@selector(selectCodeType:) forControlEvents:UIControlEventTouchUpInside];
    [sizePanel_ addSubview:select];
    
    UIButton *comfirmSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    comfirmSearch.frame = CGRectMake(0, 0, 80, 40);
    [comfirmSearch setBackgroundImage:img forState:UIControlStateNormal];
    [comfirmSearch setTitle:@"搜索" forState:UIControlStateNormal];
    comfirmSearch.center = CGPointMake(960, sizePanel_.height/2);
    comfirmSearch.right = select.left - 10;;
    [comfirmSearch addTarget:self action:@selector(comfirmSearch:) forControlEvents:UIControlEventTouchUpInside];
    [sizePanel_ addSubview:comfirmSearch];
    
    
    UIImage *searchImg = [[UIHelper getInstance] getBundleImage:@"detail_codesearch.png"];
    UIImageView *search = [[UIImageView alloc]initWithImage:searchImg];
    search.frame = CGRectMake(0, 0, searchImg.size.width*4/3, searchImg.size.height*4/3);
    search.center = CGPointMake(0, sizePanel_.height/2);
    search.right = comfirmSearch.left - 10;
    search.userInteractionEnabled=YES;
    [sizePanel_ addSubview:search];
    
    UITextField *codesearch = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 115, 50)];
    codesearch.backgroundColor = [UIColor clearColor];
    codesearch.right = comfirmSearch.left - 10;
    codesearch.inputView = [[UIView alloc]initWithFrame:CGRectZero];
    codesearch.delegate = self;
    codesearch.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    codesearch.tag = 1000;
    [sizePanel_ addSubview:codesearch];
    [self updateCodeType:codesearch];
    
    
    UIButton *copy = [UIButton buttonWithType:UIButtonTypeCustom];
    [copy setBackgroundImage:img forState:UIControlStateNormal];
    [copy setTitle:@"复制到其他店铺" forState:UIControlStateNormal];
    copy.titleLabel.font = [UIFont systemFontOfSize:14];
    copy.frame = CGRectMake(0, 0, 120, 40);
    copy.center = CGPointMake(650, sizePanel_.height/2);
    copy.right = search.left - 10;
    [copy addTarget:self action:@selector(copyToOthershop:) forControlEvents:UIControlEventTouchUpInside];
    [sizePanel_ addSubview:copy];

}

- (void)comfirmSearch:(UIButton *)sender{
    
    if (modified_) {
        [self showSavePopup];
        return;
    }
    
    UITextField *f = (UITextField *)[sizePanel_ viewWithTag:1000];
    NSString *s = f.text;
    
    if (s==nil  || s.length ==0) {
        return;
    }
//    [items removeAllObjects];
//    items = [NSMutableArray array];
    if (searchType_ == 0) {
        
        int cnt =[[[DataManager sharedManager]searchProductCountWithSimCode:s]intValue];
        
        if(cnt == 0){
            showMessage(@"没有找到对应简码");
        }
        else if(cnt >= 1){

            
            searchArray_ = [[DataManager sharedManager]searchProductWithSimCode:s];
            
            if (searchArray_.count ==1) {
                ProductObject *obj = [searchArray_ objectAtIndex:0];
                [self setup:obj];
                [self setupProduct:obj withSizeGroup:currentSelectType_];
            }
            else{
                ShopViewController *controller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain
                                                                                     items:searchArray_
                                                                                       tag:11];
                
                FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
                popover.tint = FPPopoverDefaultTint;
                if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                    popover.contentSize = CGSizeMake(300, 500);
                }
                popover.arrowDirection = FPPopoverArrowDirectionUp;
                [popover presentPopoverFromView:f];
            }
        }
        
    }
    else if(searchType_==1)
    {
        searchArray_ = [[DataManager sharedManager] searchProductWithCode:s];
        ShopViewController *controller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain
                                                                             items:searchArray_
                                                                               tag:11];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(300, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        [popover presentPopoverFromView:f];
    }
}


- (void)selectCodeType:(UIButton *)sender{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *setsearchstr = [def objectForKey:@"setsearchbtn"];
    if ([setsearchstr intValue]==0) {
        [def setObject:@"1" forKey:@"setsearchbtn"];
    }else{
        [def setObject:@"0" forKey:@"setsearchbtn"];
    }
    [def synchronize];
    
    if ([setsearchstr intValue]==0) {
        showMessage([NSString stringWithFormat:@"切换成%@",SEARCH_CODENAME]);
    }else{
        showMessage([NSString stringWithFormat:@"切换成%@",SEARCH_SIMCODE]);
    }
    
    [self updateCodeType:(UITextField *)[sizePanel_ viewWithTag:1000]];
}

- (void)copyToOthershop:(UIButton *)sender{
    UserObject *user = [[DataManager sharedManager] getUserObject];
    if (user.inputType!=2) {
        showMessage(@"该用户不能使用iPad提交订单");
        return;
    }
    
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    if (!shopobj) {
        showMessage(@"用户没有与任何店铺关联，不能提交订单");
        return;
    }
    
    if (modified_) {
        showMessage(@"复制前请先保存您的订单");
        return;
    }

    NSArray *shop = [[DataManager sharedManager] getWrittenShopList];
    if(shop.count<2){
        showMessage(@"您没有其他可以下单复制的店铺");
    }
    
    
    CopyPanel *panel = [[CopyPanel alloc] initWithFrame:CGRectMake(0, 0, 1024, 768) withCopyFlag:NO];
    panel.targetObjects = currentGridProducts_;
    [self.view addSubview:panel];
}

- (void)updateCodeType:(UITextField *)field{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *setsearchstr = [def objectForKey:@"setsearchbtn"];
    searchType_ = [setsearchstr intValue];
    
    if (searchType_) {
        field.placeholder = SEARCH_CODENAME;
    }
    else{
        field.placeholder = SEARCH_SIMCODE;
    }
}


#pragma mark 保存提示的按钮响应事件
- (void)savePopupSave{
    [backview_ removeFromSuperview];
    backview_ = nil;
    modified_ = NO;
    [self saveOrderToDatabase];
}

- (void)savePopupCancel{
    [backview_ removeFromSuperview];
    backview_ = nil;
    modified_ = NO;
    if (shouldExit_) {
        [self back];
    }
    
}

#pragma mark 添加二维码扫描按钮
- (void)addScanButton{
    UIButton *zbar = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"zbar.png"];
    [zbar setBackgroundImage:img forState:UIControlStateNormal];
    zbar.frame = CGRectMake(10, 10, img.size.width, img.size.height);
    zbar.tag = 13;
    [zbar addTarget:self action:@selector(zbar:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *r = [[UIBarButtonItem alloc] initWithCustomView:zbar];
    self.navigationItem.rightBarButtonItem = r;
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width1,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width1 = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width1, height);
}

- (void)zbar:(UIButton *)sender{
//    ZBarReaderViewController *reader = [ZBarReaderViewController new];
//    reader.readerDelegate = self;
//    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(512, 368);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//    CGRect scanMaskRect;
//    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
//        scanMaskRect = CGRectMake(0, 0, imageview.size.width, imageview.size.height);
//    }
//    else{
//        scanMaskRect = CGRectMake(0, 0, 1024, 768);
//    }
//    reader.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:reader.view.bounds];
//    
//    ZBarImageScanner *scanner = reader.scanner;
//    
//    [scanner setSymbology: ZBAR_I25
//                   config: ZBAR_CFG_ENABLE
//                       to: 0];
//    
//    
//    [self presentModalViewController: reader
//                            animated: YES];
}

#pragma mark 二维码扫描委托
//#warning 需要测试
//- (void) imagePickerController: (UIImagePickerController*) reader
// didFinishPickingMediaWithInfo: (NSDictionary*) info
//{
//    id<NSFastEnumeration> results =
//    [info objectForKey: ZBarReaderControllerResults];
//    ZBarSymbol *symbol = nil;
//    for(symbol in results)
//        break;
//    
////    UIImage *image = [info objectForKey: UIImagePickerControllerOriginalImage];
//    [reader dismissModalViewControllerAnimated: YES];
//    
//    //  zbarlabel.text =  symbol.data ;
//    int cnt =[[[DataManager sharedManager]searchProductCountWithSimCode:symbol.data]intValue];
//    if(cnt == 0)
//    {
//        NSString *str = [NSString stringWithFormat:@"没有找到简码%@的商品",symbol.data];
//        showMessage(str);
//    }
//    else if(cnt >= 1){
//        NSArray *array = [[DataManager sharedManager]searchProductWithSimCode:symbol.data];
//        ProductObject *obj = [array objectAtIndex:0];
//        if (cnt ==1) {
//            currentSelectType_ = 0;
//            [self setup:obj];
//            [self setupProduct:obj withSizeGroup:currentSelectType_];
//            
//        }
//    }
//}

#pragma mark 保存按钮
- (void)addSaveButton{
    UIButton *save = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    [save setBackgroundImage:img forState:UIControlStateNormal];
    [save setTitle:@"保存" forState:UIControlStateNormal];
    save.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    save.bottom = infoView_.top-20;
    save.right = 1024-20;
    [save addTarget:self action:@selector(saveOrderToDatabase) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:save];
}


#pragma mark 添加数字键盘
- (void)addInputPad{
    if (inputPad_) {
        [inputPad_ removeFromSuperview];
        inputPad_ = nil;
    }
    inputPad_ = [[NumberInputView alloc]initWithFrame:CGRectMake(0, 0, 260, 290)];
    inputPad_.backgroundColor = [UIColor colorWithRed:239/255.0 green:240/255.0 blue:241/255.0 alpha:1.0];
    inputPad_.delegate = self;
    inputPad_.tag = 180002;
    inputPad_.right = 1024 - 30;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0){
        inputPad_.bottom = 748-10;
    }else{
        inputPad_.bottom = 748-50;
    }
    
    [self.view addSubview:inputPad_];
}


#pragma mark 显示产品详情
- (void)displayProductInfo:(ProductObject *)product{
    if ([detailProduct_ isTheSameProduct:product]) {
        return;
    }
    
    if (infoView_) {
        [infoView_ removeFromSuperview];
        infoView_ = nil;
    }
    
    detailProduct_ = product;
    
    infoView_ = [[UIView alloc] initWithFrame:CGRectMake(0, 430, 700, 350)];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0){
        infoView_.top = 450;
    }else{
        infoView_.top = 400;
    }
    [self.view addSubview:infoView_];
    
    UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(0, -20, 1024, 1)];
    [infoView_ addSubview:sep];
    sep.backgroundColor = [UIColor blackColor];
    sep.layer.shadowColor = [UIColor darkGrayColor].CGColor;
    sep.layer.shadowOffset = CGSizeMake(0, 3);
    sep.layer.shadowOpacity = 1;
    
    //商品信息
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(20, 320, 150, 40)];
    title.bottom = sep.top;
    title.backgroundColor = [UIColor clearColor];
    title.textColor = [UIColor blackColor];
    NSString *minnumstr = [NSString stringWithFormat:@"最小起订量：%d件",[product.item5 intValue]];
    title.text = minnumstr;
    [infoView_ addSubview:title];
    
    UILabel *title1 = [[UILabel alloc]initWithFrame:CGRectMake(230, 320, 150, 40)];
    title1.backgroundColor = [UIColor clearColor];
    title1.bottom = sep.top;
    title1.textColor = [UIColor blackColor];
    NSString *minnumstr1 = [NSString stringWithFormat:@"订货倍数：%d",[product.n_beis intValue]];
    title1.text = minnumstr1;
    [infoView_ addSubview:title1];
    
    
    //商品详情
    UIScrollView *detailscroll = [[UIScrollView alloc]initWithFrame:CGRectMake(300, 0, 400, infoView_.height)];
    detailscroll.backgroundColor = [UIColor clearColor];
    detailscroll.clipsToBounds = YES;
    [infoView_ addSubview:detailscroll];
    
    UILabel *titlecell = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, detailscroll.width-20, 30)];
    titlecell.backgroundColor = [UIColor clearColor];
    titlecell.text = [NSString stringWithFormat:@"商品详情(%@)",product.pColor];
    titlecell.textColor = [UIColor colorWithRed:57/255.0 green:14/255.0 blue:0 alpha:1.0];
    titlecell.textAlignment = NSTextAlignmentLeft;
    titlecell.adjustsFontSizeToFitWidth = YES;
    titlecell.font = [UIFont systemFontOfSize:28];
    [detailscroll addSubview:titlecell];

    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, detailscroll.width-20, 1)];
    [detailscroll addSubview:line];
    line.backgroundColor = [UIColor blackColor];
    line.top = titlecell.bottom+5;
    
    float bottom=line.bottom+5;
    NSArray *array = [[DataManager sharedManager]getSpdmOrder];
    for (int i = 0; i<array.count; i++) {
        NSDictionary *dic = [array objectAtIndex:i];
        NSString *titlename = [dic objectForKey:@"c_spdmmc"];
        NSString *name = [dic objectForKey:@"c_spdmzd"];
        NSString *isvisible = [dic objectForKey:@"b_visible"];
        if ([isvisible isEqualToString:@"0"]) {
            continue;
        }
        
        NSString *content = [product getValueByKey:name];
        
        NSString *str = [NSString stringWithFormat:@"%@：%@",titlename,content];
        if ([content isEqualToString:@""]) {
            continue;
        }
        CGSize s = [str sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:CGSizeMake(detailscroll.width-20, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        DetailcellView *cell = [[DetailcellView alloc]initWithFrame:CGRectMake(0, 0, detailscroll.width-20, s.height+1)];
        cell.top=bottom;
        cell.title.text = str;
        cell.title.font = [UIFont systemFontOfSize:20];
        bottom=cell.bottom;
        [detailscroll addSubview:cell];
        detailscroll.contentSize = CGSizeMake(detailscroll.width, bottom);
    }
    
    
    //商品图片
    productImageV_ = [[UIImageView alloc] initWithFrame:CGRectMake(25, 0, 280, 240)];
    [infoView_ addSubview:productImageV_];
    productImageV_.userInteractionEnabled = YES;
    productImageV_.clipsToBounds = YES;
    productImageV_.contentMode = UIViewContentModeScaleAspectFit;
    productImageV_.backgroundColor = [UIColor clearColor];
    NSString *url = [NSString stringWithFormat:@"%@",product.pThumbURL];
    NSString * path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
    path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
    
    if ([[PMGlobal getInstance]isImageEnable]) {
        productImageV_.image = [imageCache_ imageForKey:product.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:0];
        if (!productImageV_.image) {
            productImageV_.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
        }
    }else{
        productImageV_.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBigImage)];
    [productImageV_ addGestureRecognizer:tap];
    
    
    UIView *imagebar = [[UIView alloc]initWithFrame:CGRectMake(productImageV_.left, 0, productImageV_.width, 40)];
    imagebar.backgroundColor = [UIColor colorWithRed:177/255.0 green:177/255.0 blue:177/255.0 alpha:1];
    imagebar.top = productImageV_.bottom + 20;
    [infoView_ addSubview:imagebar];
    
    UIImage *img = [[UIHelper getInstance]getBundleImage:@"price.png"];
    UIImageView *price = [[UIImageView alloc]initWithImage:img];
    price.center = CGPointMake(price.width/2, imagebar.height/2);
    [imagebar addSubview:price];
    
    UILabel *sale = [[UILabel alloc]initWithFrame:CGRectMake(price.right, 0, 100, imagebar.height)];
    sale.backgroundColor = [UIColor clearColor];
    sale.textColor = [UIColor colorWithRed:57/255.0 green:14/255.0 blue:0 alpha:1.0];
    sale.textAlignment = UITextAlignmentLeft;
    sale.font = [UIFont systemFontOfSize:25];
    NSString *salestr = [NSString stringWithFormat:@"%.0f元",product.pSale];
    sale.text = salestr;
    [imagebar addSubview:sale];
    
    UILabelStrikeThrough *code1 = [[UILabelStrikeThrough alloc]initWithFrame:
                                   CGRectMake(0, 0, 150, imagebar.height)];
    code1.backgroundColor = [UIColor clearColor];
    code1.textColor = [UIColor colorWithRed:57/255.0 green:14/255.0 blue:0 alpha:1.0];
    code1.text = product.pCode;
    code1.font = [UIFont systemFontOfSize:25];
    code1.textAlignment = NSTextAlignmentRight;
    code1.right = imagebar.width-5;
    [imagebar addSubview:code1];
    if ([product.n_status intValue]==1) {
        code1.textColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:1];
        code1.isWithStrikeThrough = YES;
    }
    
    
    UIView *collectback = [[UIView alloc]initWithFrame:CGRectMake(0, 0, productImageV_.width, 45)];
    collectback.backgroundColor = [UIColor colorWithRed:177/255.0 green:177/255.0 blue:177/255.0 alpha:0.55];
    collectback.right = productImageV_.right;
    collectback.bottom = productImageV_.bottom;
    [infoView_ addSubview:collectback];
    
    
    int favLevel = [[DataManager sharedManager]productIsFavorite:product Shopid:shopObj_.shopID];
    
    UIImage *favImage = [[UIHelper getInstance] getBundleImage:@"collect_image.png"];
    UIImage *favHImage = [[UIHelper getInstance] getBundleImage:@"collect_redimage.png"];
    for (int i = 0; i<5; i++) {
        UIButton *collect = [UIButton buttonWithType:UIButtonTypeCustom];
        if (i<favLevel) {
            [collect setBackgroundImage:favHImage forState:UIControlStateNormal];
        }
        else{
            [collect setBackgroundImage:favImage forState:UIControlStateNormal];
        }
        collect.frame = CGRectMake( 0, 0, favHImage.size.width, favHImage.size.height);
        collect.center = CGPointMake(0, collectback.height/2);
        collect.left = i*50+20;
        collect.tag = i;
        [collect addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
        [collectback addSubview:collect];
    }

}

#pragma mark 显示产品图片
- (void)product_detail_image:(NSNotification *)notification{
    NSDictionary *dict = [notification userInfo];
    UIImage *img = [dict objectForKey:@"image"];
    //int tag = [[dict objectForKey:@"tag"] intValue];
    
    if ([[PMGlobal getInstance]isImageEnable]) {
        if (img) {
            productImageV_.image = img;
        }else{
        }
    }else{
        productImageV_.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
    }
}


#pragma mark 点击收藏
- (void)collect:(UIButton *)sender{
    int star = sender.tag+1;
    int favLevel = [[DataManager sharedManager]productIsFavorite:selectProduct_ Shopid:shopObj_.shopID];
    if (star==favLevel) {
        [[DataManager sharedManager] cancelAsFavorite:selectProduct_ Shopid:shopObj_.shopID];
    }else{
        [[DataManager sharedManager]setAsFavorite:selectProduct_ withStar:star Shopid:shopObj_.shopID type:@"0"];
    }
    detailProduct_ = nil;
    [self displayProductInfo:selectProduct_];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"collectreload" object:productObject_];
}

#pragma mark 数字键盘的委托
- (void)numberInputViewDidClick:(NSString *)clickValue{
    
    int val = [clickValue intValue];
    
    
    
    int tag = currentSelectInput_.tag;
    
    if (tag>=100000) {//尺码输入框
        
        currentSelectInput_.text = [NSString stringWithFormat:@"%d",val];
        
        int line = (tag - 100000)/10000;
        int sizeIndex = ((tag-100000)%10000)/100;
        
        ProductObject *obj = [currentGridProducts_ objectAtIndex:line];
        
        OrderObject *order = [self getOrder:obj];
        SizeObject *sizeobj = [currentGridSizes_ objectAtIndex:sizeIndex];
        [order setOrder:sizeobj.sSizeNo withQuantity:[clickValue intValue] withShopID:shopObj_.shopID];
        
        [self displayProductInfo:obj];
        
        [self refreshSubtotal];
        
        modified_ = YES;
        
    }else{
        currentSelectInput_.text = clickValue;
    }
    
}

- (void)numberInputViewEnterClick:(NSString *)clickValue{
    int tag = currentSelectInput_.tag;
    
    if (tag>=100000) {//尺码输入框
        int line = (tag - 100000)/10000;
        int sizeIndex = ((tag-100000)%10000)/100+1;//如果有下一个尺码，那么下一个尺码的输入框变为激活状态
        
        ProductObject *obj = [currentGridProducts_ objectAtIndex:line];
        OrderObject *order = [self getOrder:obj];
        
        if (sizeIndex<currentGridSizes_.count) {
            SizeObject *sizeObj = [currentGridSizes_ objectAtIndex:sizeIndex];
            NSString *key = [NSString stringWithFormat:@"%@_%@",sizeObj.sSizeNo,shopObj_.shopID];
            UITextField *l = (UITextField *)([order.pParam objectForKey:key]);
            [l becomeFirstResponder];
        }
        
    }else{
        [self comfirmSearch:nil];
    }
    
}

#pragma mark 刷新小计
- (void)refreshSubtotal{
    
    
    int total = 0;
    for (int i = 0; i < currentSubtotal_.count;i++) {
        UILabel *l = (UILabel *)[currentSubtotal_ objectAtIndex:i];
        ProductObject *obj = [currentGridProducts_ objectAtIndex:i];
        OrderObject *order = [self getOrder:obj];
        
        int amount = [order getOrderNumberBySize:currentGridSizes_];
        total += amount;
        
        l.text = [NSString stringWithFormat:@"%d",amount];
    }
    
    
    totalAmountLabel_.text = [NSString stringWithFormat:@"总订单数 :  %d",total];
}

#pragma mark 显示表格
- (void)displayProductGrid:(NSArray *)products xLarge:(NSArray *)largeProducts size:(NSArray *)sizes{
    
    float widthColor = 200;
    float widthPrice = 75;
    float widthSuit = 75;
    float widthSize = 75;
    float widthTotal = 50;
    float widthOpt = 80;
    
    float gridHeight = 35;
    
    currentGridSizes_ = [NSMutableArray arrayWithArray:sizes];
    currentSubtotal_ = [NSMutableArray array];
    currentGridProducts_ = [NSMutableArray arrayWithArray:products];
    if (largeProducts!=nil && largeProducts.count>0) {
        [currentGridProducts_ addObjectsFromArray:largeProducts];
    }
    
    
    UIColor *borderColor = [UIColor lightGrayColor];
    
    if (gridScroll_) {
        [gridScroll_ removeFromSuperview];
        gridScroll_ = nil;
    }
    
    
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, sizePanel_.bottom+4, 1024, 250)];
    [self.view addSubview:scroll];
    scroll.backgroundColor = [UIColor clearColor];
    gridScroll_ = scroll;
    
    //表头：颜色 + 尺码 + 总计 + 操作
    
    //创建表头
    float yOffset =  0;
    
    UIScrollView *sizeScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(widthColor, 0, 1024-widthColor-widthTotal-widthOpt-widthSuit-widthPrice, scroll.height)];
    sizeScroll.showsHorizontalScrollIndicator = NO;
    
    float w = sizeScroll.width/sizes.count;
    if (w > widthSize) {
        widthSize = w;;
    }
    
    
    sizeScroll.backgroundColor = [UIColor clearColor];
    [scroll addSubview:sizeScroll];
    
    for (int line = 0; line < products.count+largeProducts.count+1; line++) {
        
        ProductObject *obj = nil;
        
        OrderObject *order = nil;
        
        if (line>0) {
            obj = [currentGridProducts_ objectAtIndex:line-1];
            
            order = [self getOrder:obj];
            
        }
        
        UIColor *cellBackground = nil;
        if (line==0) {
            cellBackground = [UIColor colorWithWhite:1 alpha:1];
        }else{
            if ([obj.n_status intValue]==0) {
                cellBackground = [UIColor colorWithWhite:0 alpha:1];
            }else{
                cellBackground = [UIColor colorWithRed:1 green:0 blue:0 alpha:1];
            }
            
        }
        
        float xOffset = 0;
        
        int size_start = 3;
        
        for (int i = 0; i < sizes.count + size_start + 2; i++) {
            if (i==0) {
                UILabel *cell = [[UILabel alloc] initWithFrame:CGRectMake(xOffset, yOffset, widthColor, gridHeight)];
                cell.layer.borderWidth=1;
                cell.layer.borderColor = borderColor.CGColor;
                
                cell.textAlignment = NSTextAlignmentCenter;
                [scroll addSubview:cell];
                
                cell.textColor = cellBackground;
                if (obj) {
                    cell.text =[NSString stringWithFormat:@"%@", obj.pColor];
                    cell.adjustsFontSizeToFitWidth = YES;
                    cell.backgroundColor = [UIColor clearColor];
                }else{
                    cell.text = @"商品规格";
                    cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                }
                
                
            }else if(i==1){
                UILabel *cell = [[UILabel alloc] initWithFrame:CGRectMake(widthColor, yOffset, widthPrice, gridHeight)];
                cell.layer.borderWidth=1;
                cell.layer.borderColor = borderColor.CGColor;
                
                cell.textAlignment = NSTextAlignmentCenter;
                [scroll addSubview:cell];
                
                cell.textColor = cellBackground;
                
                if (obj) {
                    cell.text =[NSString stringWithFormat:@"%.0f", obj.pSale];
                    cell.adjustsFontSizeToFitWidth = YES;
                    cell.backgroundColor = [UIColor clearColor];
                }else{
                    cell.text = @"指导价";
                    cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                }
                
                sizeScroll.left = cell.right;
            }
            else if(i==2){
                UILabel *cell = [[UILabel alloc] initWithFrame:CGRectMake(widthColor+widthPrice, yOffset, widthSuit, gridHeight)];
                cell.layer.borderWidth=1;
                cell.layer.borderColor = borderColor.CGColor;
                
                cell.textAlignment = NSTextAlignmentCenter;
                [scroll addSubview:cell];
                
                cell.textColor = cellBackground;
                
                if (obj) {
                    cell.text =[NSString stringWithFormat:@"%@", [obj getValueByKey:@"barcode"]];
                    cell.adjustsFontSizeToFitWidth = YES;
                    cell.backgroundColor = [UIColor clearColor];
                }else{
                    cell.text = @"装箱数";
                    cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                }
                
                sizeScroll.left = cell.right;
            }else if(i < sizes.count+size_start && i >size_start-1){
                
                UIView *cell = [[UIView alloc] initWithFrame:CGRectMake( (i-size_start)*widthSize, yOffset, widthSize, gridHeight)];
                cell.layer.borderWidth=1;
                cell.layer.borderColor = borderColor.CGColor;
                
                UIImageView *imgV = [[UIImageView alloc] initWithFrame:cell.bounds];
                [cell addSubview:imgV];
                imgV.tag = 1;
                //xOffset = cell.right-1;

                UITextField *l = [[UITextField alloc] initWithFrame:cell.bounds];
                l.delegate = self;
                [cell addSubview:l];
                l.textColor = cellBackground;
                l.tag = 100000 + (line-1) * 10000 + (i-size_start) * 100;
                l.textAlignment = NSTextAlignmentCenter;
                l.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                l.inputView = [[UIView alloc] initWithFrame:CGRectZero];
                
                [sizeScroll addSubview:cell];

                SizeObject *sizeObj = [sizes objectAtIndex:i-size_start];

                if (obj) {
                    NSString *key = [NSString stringWithFormat:@"%@_%@",sizeObj.sSizeNo,shopObj_.shopID];
                    l.text = [NSString stringWithFormat:@"%d",[[order.quantity objectForKey:key] intValue]];
                    [order setOrderControl:sizeObj.sSizeNo withShopID:shopObj_.shopID view:l];
                    cell.backgroundColor = [UIColor clearColor];
                }else{
                    l.text = sizeObj.sSizeName;
                    cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                    l.userInteractionEnabled = NO;
                }
                
                sizeScroll.contentSize = CGSizeMake(cell.right, l.bottom);
                
            }else if(i == sizes.count+size_start){
                UILabel *cell = [[UILabel alloc] initWithFrame:CGRectMake(sizeScroll.right, yOffset, widthTotal, gridHeight)];
                cell.layer.borderWidth=1;
                cell.layer.borderColor = borderColor.CGColor;
                cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                cell.textAlignment = NSTextAlignmentCenter;
                [scroll addSubview:cell];
                if (line==0) {
                    cell.text = @"小计";
                    cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                }else{
                    cell.text = [NSString stringWithFormat:@"%d",[order getOrderNumberBySize:sizes]];
                    cell.backgroundColor = [UIColor clearColor];
                    
                    [currentSubtotal_ addObject:cell];
                }
            }else if(i == sizes.count+size_start+1){
                UILabel *cell = [[UILabel alloc] initWithFrame:CGRectMake(sizeScroll.right+widthTotal, yOffset, widthOpt, gridHeight)];
                cell.layer.borderWidth=1;
                cell.layer.borderColor = borderColor.CGColor;
                cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                cell.textAlignment = NSTextAlignmentCenter;
                cell.userInteractionEnabled = YES;
                [scroll addSubview:cell];
                if (line==0) {
                    cell.text = @"操作";
                    cell.backgroundColor = [UIColor colorWithRed:180/255.0 green:145/255.0 blue:106/255.0 alpha:1];;
                }else{
                    UIImage *img3 = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
                    UIButton *proportion = [UIButton buttonWithType:UIButtonTypeCustom];
                    [proportion setBackgroundImage:img3 forState:UIControlStateNormal];
                    proportion.frame = CGRectMake(0, 0, cell.width-10, cell.height-5);
                    proportion.center = CGPointMake(cell.width/2, cell.height/2);
                    [proportion setTitle:@"清除" forState:UIControlStateNormal];
                    [proportion addTarget:self action:@selector(clearOrder:) forControlEvents:UIControlEventTouchUpInside];
                    [cell addSubview:proportion];
                    cell.backgroundColor = [UIColor clearColor];
                    proportion.tag = line-1;
                }
            }
            
            
        }
        yOffset += gridHeight-1;
        UIView *l = [[UIView alloc] initWithFrame:CGRectMake(xOffset, yOffset, scroll.width-xOffset*2, 1)];
        l.backgroundColor = [UIColor darkGrayColor];
        [scroll addSubview:l];
        
        if (line==1) {
            UILabel *v = [[UILabel alloc] initWithFrame:CGRectMake(xOffset, yOffset, scroll.width-xOffset*2, 0)];
            v.backgroundColor = [UIColor colorWithRed:209/255.0 green:194/255.0 blue:176/255.0 alpha:1];;
            [scroll addSubview:v];
            v.text = @"同款其他";
            v.font = [UIFont systemFontOfSize:13];
            v.textAlignment = NSTextAlignmentCenter;
            v.hidden = YES;
//            yOffset += v.height-1;
        }
        
#ifdef XLarge_ENABLE
        if(line == products.count){
            UILabel *v = [[UILabel alloc] initWithFrame:CGRectMake(xOffset, yOffset, scroll.width-xOffset*2, 20)];
            v.backgroundColor = [UIColor colorWithRed:209/255.0 green:194/255.0 blue:176/255.0 alpha:1];;
            [scroll addSubview:v];
            v.text = @"加大款";
            v.font = [UIFont systemFontOfSize:13];
            v.textAlignment = NSTextAlignmentCenter;
            yOffset += v.height-1;
        }
#endif
        
    }
    
    sizeScroll.height = yOffset;
    scroll.contentSize = CGSizeMake(scroll.width, yOffset);
    
    
    [self refreshSubtotal];
    
}


#pragma mark 清除
- (void)clearOrder:(UIButton *)sender{
    
    ProductObject *obj = [currentGridProducts_ objectAtIndex:sender.tag];
    OrderObject *order = [self getOrder:obj];
    if (currentSizeType_.count==1) {
        [order clearOrder];
    }else{
        
        [order clearOrderBySize:currentGridSizes_];
    }
    [self refreshSubtotal];
    
    inputPad_.value = @"";
    modified_ = YES;
}

#pragma mark 多尺码点击
- (void)selectSizeType:(UIButton *)sender{
    
    selectProduct_ = productObject_;
    int tag = sender.tag;
    currentSelectType_ = tag;
    [self setupProduct:selectProduct_ withSizeGroup:tag];
}

#pragma mark 加裤按钮被点击
- (void)jkClick{
    ProductObject *jkProduct = (ProductObject *)[additionProduct objectForKey:@"4"];
    selectProduct_ = jkProduct;
    //[self setupProduct:selectProduct_ withSizeGroup:0];
    [self displayProductInfo:jkProduct];
    
    NSArray *sizes = [[DataManager sharedManager] getSizeListBySizeGroup:jkProduct.pSizeGroupID
                                                                SizeType:nil];
    
    NSMutableArray *products = [NSMutableArray arrayWithObjects:jkProduct, nil];
    
    NSArray *similar = [[DataManager sharedManager] getSimiliarProduct:jkProduct];
    [products addObjectsFromArray:similar];
    
    [self displayProductGrid:products xLarge:nil size:sizes];
}

#pragma mark UITextField 委托
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if (textField.tag>=100000) {
        NSString *msg = [self canPlaceOrder];
        if (msg!=nil) {
            showMessage(msg);
            return NO;
        }
        
        ProductObject *line = [currentGridProducts_ objectAtIndex:(textField.tag-100000)/10000];
        
        if ([line.n_status intValue]!=0) {
            showMessage(@"该款为取消款，不能下单");
            return NO;
        }
        
        if (currentSelectInput_ == textField) {
            return YES;
        }
        
        if (currentSelectInput_ && currentSelectInput_.tag>=100000) {
            UIImageView *v = (UIImageView *)[currentSelectInput_.superview viewWithTag:1];
            v.image = nil;
        }
        inputPad_.value = nil;;
        
        currentSelectInput_ = textField;
        
        
        UIImageView *v = (UIImageView *)[currentSelectInput_.superview viewWithTag:1];
        v.image = [[UIHelper getInstance] getBundleImage:@"order_click.png"];
        
        
        
        [self displayProductInfo:line];
        
        return YES;
    }else{
        
        if (currentSelectInput_ && currentSelectInput_.tag>=100000) {
            UIImageView *v = (UIImageView *)[currentSelectInput_.superview viewWithTag:1];
            v.image = nil;
        }
        
        inputPad_.value = @"";
        
        currentSelectInput_ = textField;
        
        return YES;
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark 判断是否有下单的权限
- (NSString *)canPlaceOrder{
    UserObject *user = [[DataManager sharedManager] getUserObject];
    if (user.inputType!=2) {
        //showMessage(@"该用户不能使用iPad提交订单");
        return @"该用户不能使用iPad提交订单";
    }
    
    if (!shopObj_||[shopObj_.shopID isEqualToString:@""]||shopObj_.shopID == nil) {
        return @"用户没有与任何店铺关联，不能提交订单";
    }
    
    if (shopObj_.bCheck) {
        return @"该店铺已经审核，不能提交订单";
    }
    
    if ([shopObj_.bOrder intValue]==0) {
        return @"该用户没有录单权限";
    }
    
    return nil;
}

#pragma 获取订单object
- (OrderObject *)getOrder:(ProductObject *)product{
    NSString *key = [NSString stringWithFormat:@"%@_%@",product.pCode,product.pColorCode];
    OrderObject *obj = [currentGridOrders_ objectForKey:key];
    if (obj==nil) {
        obj = [[DataManager sharedManager] getOrderByProduct:product Shopid:shopObj_.shopID];
        [currentGridOrders_ setObject:obj forKey:key];
    }
    
    return obj;
}

#pragma mark 保存订单到数据库
-(void)saveOrderToDatabase{
    
    int error = 0;
    int times = 0;
    for (OrderObject *order in currentGridOrders_.allValues) {
        
        for (ProductObject *obj in currentGridProducts_) {
            if ([obj.pCode isEqualToString:order.pCode] &&
                [obj.pColorCode isEqualToString:order.pColorCode]) {
                int total = [order getTotalOrderNumber];
                if (total != 0 && total < [obj.item5 intValue]) {
                    error = 1;//小于最小起订量
                    break;
                }else if(total%[obj.n_beis intValue] != 0){
                    error = 2;//非倍数订货
                    times = [obj.n_beis intValue];
                }
            }
        }
        
        if (error!=0) {
            break;
        }
    }
    
    if (error==1) {
        showMessage(@"订货量不能小于最小订货量");
        return;
    }else if(error==2){
        showMessage([NSString stringWithFormat:@"订货量必须是%d的倍数",times]);
        return;
    }
    

    [WaitTooles showHUD:@"正在保存"];
    
    [[AppManager sharedManager] pauseAutoSubmitSession];
    [[AppManager sharedManager] pauseAutoUpdateSession];
    
//    dispatch_queue_t save_queue = dispatch_queue_create("com.yx.pm.save", NULL);
//    dispatch_async(save_queue, ^(void) {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
//    dispatch_async(dispatch_get_main_queue(), ^{
        for (OrderObject *order in currentGridOrders_.allValues) {
            [[DataManager sharedManager]placeOrder:order];
        }

        
    
            [WaitTooles removeHUD];
            
            for (OrderObject *order in currentGridOrders_.allValues) {
                
                ProductObject *p = [[ProductObject alloc] init];
                p.pColorCode = order.pColorCode;
                p.pCode = order.pCode;
                [[NSNotificationCenter defaultCenter]postNotificationName:@"numreload"
                                                                   object:p];
            }
            
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                               object:nil];

            if (shouldExit_) {
                [self back];
            }
            shouldExit_ = NO;
            
            modified_ = NO;
        
    });

//    });
}

- (void)coderefresh:(NSNotification *)notification{
    NSString *num = notification.object;
    ProductObject *obj = [searchArray_ objectAtIndex:[num intValue]];
    [self setup:obj];
    [self setupProduct:obj withSizeGroup:currentSelectType_];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}

#pragma mark 显示大图
- (void)showBigImage{
    NSString *url = [NSString stringWithFormat:@"%@",detailProduct_.pURL];
    NSString * path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
    path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
    NSArray *array = [NSArray arrayWithObject:path];
    PictureViewController *pic = [[PictureViewController alloc] initWithPictures:array withFrame:self.view.frame Desc:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:pic];
    UIImage *img = [[PMGlobal getInstance]getnavigationbarimage];
    [nav.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController presentModalViewController:nav animated:YES];
    
}
@end
